package com.zsj.zsjkotlinmvvm.data.remote.repository

import com.zsj.zsjkotlinmvvm.data.model.ListData
import com.zsj.zsjkotlinmvvm.data.model.repository.*
import com.zsj.zsjkotlinmvvm.utils.dateFormatForRepository
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Query
import java.time.LocalDateTime
import javax.inject.Inject

/**
 * Created by TanJiaJun on 2020/4/4.
 */
class RepositoryRemoteDataSource @Inject constructor(
    retrofit: Retrofit
) {

    private val service: Service = retrofit.create(Service::class.java)

    suspend fun fetchRepositories(
        languageName: String,
        fromDateTime: LocalDateTime
    ): List<RepositoryData> =
        service
            .fetchRepositories(
                query = "language:${languageName} created:>${
                    fromDateTime.format(
                        dateFormatForRepository()
                    )
                }",
                sort = "stars"
            )
            .items
            ?.map { RepositoryMapper.toRepositoryData(it) }
            ?: emptyList()


    interface Service {

        @GET("search/repositories")
        suspend fun fetchRepositories(
            @Query("q") query: String,
            @Query("sort") sort: String
        ): ListData<RepositoryResponseData>


    }

}